//
// Created by vista on 2017/12/17.
//

#ifndef P_P19_H
#define P_P19_H

#include <vector>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <iostream>
#include <stack>
#include <set>
using namespace std;

#ifndef NULL
#define NULL 0
#endif

struct ListNode {
    int val;
    ListNode *next;

    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int total = 0;
        ListNode * ptr = head;
        while (ptr != NULL){
            ++total;
            ptr = ptr->next;
        }
        int index = total - n ;

        total = 0;

        ptr = head;
        ListNode * last;

        if(index == 0){
            return head->next;
        }

        while (ptr != NULL){
            if(total == index){
                last->next = ptr->next;

                break;

            }else{
                ++total;
                last = ptr;
                ptr = ptr->next;
            }
        }

        return head;
    }
};

#endif //P_P19_H
